/*
 * @Author: 李超越 1509572300@qq.com
 * @Date: 2024-09-28 11:58:17
 * @LastEditors: 李超越 1509572300@qq.com
 * @LastEditTime: 2024-09-28 19:07:44
 * @FilePath: /my_git/lesson34_tcpserver/TcpServer.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace std;

const static int defaultsockfd = -1;
const static int backlog = 16;

enum
{
    SOCKET_ERROR=1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

class TcpServer
{
private:
public:
    TcpServer(int port):_port(port),_listensock(defaultsockfd)
    {}

    void InitServer()
    {
        //创建流式套接字
        _listensock = ::socket(AF_INET, SOCK_STREAM, 0);
        if(_listensock<0)
        {
            LOG(FATAL, "socket error");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create");

        //绑定接口
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = ::bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if(n<0)
        {
            LOG(FATAL, "bind error");
            exit(BIND_ERROR);
        }

        //TCP是面向连接的，所以通信前，必须先建立起来。
        //tcpserver启动，未来首先一直等待客户链接到来
        n = ::listen(_listensock, backlog);
        if(n<0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }
    }

    void Service(int sockfd,InetAddr client)
    {
        LOG(DEBUG, "get a new link,info %s:%d", client.Ip().c_str(), client.Port());
        string clientaddr = "[" + client.Ip() + ":" + to_string(client.Port()) + "]#";
        while(true)
        {
            char inbuffer[1024];
            ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
            if(n>0)
            {
                inbuffer[n] = 0;
                cout << clientaddr << endl;
            }
            else if(n==0)//client 退出并关闭连接
            {

            }
        }
        ::close(sockfd);
    }

    void Loop()
    {
        _isrunning = true;
        while(_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensock, (struct sockaddr *)&peer, &len);
            if(sockfd<0)
            {
                LOG(WARNING, "accept error\n");
                continue;
            }
            InetAddr addr(peer);
            Service(sockfd, addr); 
            _isrunning = false;
        }
        
    }

    ~TcpServer()
    {
        if(_listensock>defaultsockfd)
        {
            ::close(_listensock);
        }
    }
private:
    uint16_t _port;
    int _listensock;
    bool _isrunning;
};